﻿using System;
using System.Composition;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Unread.Business.Data.Storage.Interfaces;
using Windows.Storage;

namespace Unread.Business.Data.Storage
{
    [Export(typeof(IRoamingStorageContext))]
    internal class RoamingStorageContext : IRoamingStorageContext
    {
        protected string FileName 
        {
            get
            {
                var fileName = ApplicationData.Current.RoamingSettings.Values[Constants.DefaultSettingsFileName];
                if (fileName == null)
                    throw new InvalidOperationException("FileName cannot be empty, set FileName first");

                return fileName.ToString();
            }
        }

        public async Task<string> ReadFile()
        {
            try
            {
                var file = await ApplicationData.Current.RoamingFolder.GetFileAsync(FileName);
                
                return await FileIO.ReadTextAsync(file);
            }
            catch (FileNotFoundException ex)
            {
                Debug.WriteLine(ex);
                return null;
            }
        }

        public async Task WriteFile(string value)
        {
            var file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(file, value);
        }
    }
}
